﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Xml.Linq;
using TripLOA.GUI.internationalization;
using TripLOA.GUI.FullTextSearch;
using log4net;

namespace TripLOA.GUI
{
    public class Global : System.Web.HttpApplication
    {
#if LOG
        private readonly ILog _logger = LogManager.GetLogger(typeof(Global));
#endif
        protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null && app.Request.FilePath.Contains("aspx"))
            {
                // Release the DataContext related to the current request.
                Storage.StorageManager.Instance.DisposeDataContext();
            }
        }

        protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null && app.Request.FilePath.Contains("aspx"))
            {
                // Force the creation of the DataContext.
                var db = Storage.StorageManager.Instance.Entities;
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            // Added by Luca Puccini on June 04 2008
            Stats.StatsModule.Init(Server.MapPath(@"\App_Data\DataFile.xml"));

            // Added by Matteo Parchi on June 26 2008
            // It starts the stats daemon which every tot hours (see implementation) update daily stats table in db
            Stats.StatsModule.startStatsDaemon();

            // Register a timer for the trips that are not accomplished.
            //initTimers();
        }

        /// <summary>
        /// Restore the timers for the pending trips.
        /// </summary>
        private void initTimers()
        {
            var db = Storage.StorageManager.Instance.Entities;

            var pendingTrips = from trip in db.Trips
                               where !trip.Accomplished
                               select trip;

            foreach (Storage.EntityModels.Trip t in pendingTrips)
            {
                // TODO: need a brand new method 'cause this one get a GroupWare.Trip not a Storage one!
                //Groupware.TripUpdater.Track(t);
            }
        }
      
        protected void Session_Start(object sender, EventArgs e)
        {
            // If it's a WebService Request skip
            string type = Context.Handler.GetType().ToString();
            if (Context.Handler is TripLOA.WebService.Rest.EndPoint ||
                type.Contains("System.Web.Script.Services.ScriptHandlerFactory"))
            {
                return;
            }
            
            // Sets the default application language 
            HttpRequest Request = HttpContext.Current.Request;
            if (Request.UserLanguages == null)
                Session[LOAGlobal.Global.SESSION_KEY_CULTURE] = LOACulture.Culture.EN;


            if ( (Request.UserLanguages != null) && (Request.UserLanguages[0] != null) )
            {
                string Lang = Request.UserLanguages[0];

                if (!Lang.Equals("en"))//da problemi se si usa en generale!
                {
                    if (Lang.Length < 3)
                        Lang = Lang + "-" + Lang.ToUpper();
                }
                else
                    Lang = LOACulture.Culture.EN;               

                // If possible use the browser language.
                Session[LOAGlobal.Global.SESSION_KEY_CULTURE] = Lang;
            }
            else
            {
                // Sets english as default startup language.
                Session[LOAGlobal.Global.SESSION_KEY_CULTURE] = LOACulture.Culture.EN;
            }


            // Stores in session a new FullTextSearchProperties object
            Session[LOAGlobal.Global.SESSION_KEY_FTSEARCH_PROPERTIES] = new FullTextSearchProperties();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
        }

        protected void Application_Error(object sender, EventArgs e)
        {
#if LOG
            _logger.Error(sender);
#endif
            // Release the DataContext related to the current request.
            //Storage.StorageManager.Instance.DisposeDataContext();
        }

        protected void Session_End(object sender, EventArgs e)
        {
        }

        protected void Application_End(object sender, EventArgs e)
        {
        }
    }
}